package com.gmail.avereshchaga.web.transport;

import com.gmail.avereshchaga.db.entity.IUser;
import com.gmail.avereshchaga.db.entity.IUserSessionId;
import com.gmail.avereshchaga.db.entity.UserSessionIdImpl;
import com.gmail.avereshchaga.db.service.IUserService;
import com.gmail.avereshchaga.db.service.IUserSessionIdService;
import com.gmail.avereshchaga.tools.RandomGeneration;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * Class defines the functions of creating and closing session
 *
 * @author <a href="mailto:avereshchaga@gmail.com">Vereshchaga Alexey</a>
 */
@Controller
public class UserSessionIdTransport {

    @Autowired
    private IUserSessionIdService userSessionIdService;
    @Autowired
    private IUserService userService;

    /**
     * Call method of create session
     *
     * @param username user name for which the session is created
     * @param password password of the user
     * @return information list about the creation of the session
     */
    @RequestMapping(value = "connection")
    @ResponseBody
    public List createSession(@RequestParam("username") String username,
            @RequestParam("password") String password) {
        IUser user;
        List<String> sessionIdInfo = new ArrayList();
        user = userService.findByUsernameAndPassword(username, password);
        if (user != null) {
            Long sessionId = new RandomGeneration().getRandom();
            IUserSessionId userSessionId = new UserSessionIdImpl();

            userSessionId.setUser(user);
            userSessionId.setSessionId(sessionId);
            userSessionIdService.createUserSessionId(userSessionId);

            sessionIdInfo.add("Success Connection");
            sessionIdInfo.add(sessionId.toString());
            sessionIdInfo.add(user.getAccessLevel());
        } else {
            sessionIdInfo.add("Connection Error");
        }
        return sessionIdInfo;
    }

    /**
     * Calls the method of closing sessions
     *
     * @param username user name for which the session is created
     * @param password password of the user
     */
    @RequestMapping(value = "closeSession")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void closeSession(@RequestParam("username") String username,
            @RequestParam("password") String password) {
        userSessionIdService.closeSession(username, password);
    }
}
